package com.bjpowernode.service.impl;

import com.alibaba.excel.EasyExcel;
import com.bjpowernode.config.listener.UploadDataListener;
import com.bjpowernode.constant.Constants;
import com.bjpowernode.mapper.TClueMapper;
import com.bjpowernode.model.TClue;
import com.bjpowernode.query.BaseQuery;
import com.bjpowernode.query.ClueQuery;
import com.bjpowernode.service.ClueService;
import com.bjpowernode.util.JWTUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
public class ClueServiceImpl implements ClueService {

    @Resource
    private TClueMapper tClueMapper;

    @Override
    public PageInfo<TClue> getClueByPage(Integer current) {
        PageHelper.startPage(current, Constants.PAGE_SIZE);
        List<TClue> list = tClueMapper.selectClueByPage(BaseQuery.builder().build());
        PageInfo<TClue> info = new PageInfo<>(list);
        return info;
    }

    @Override
    public void importExcel(MultipartFile file, String token) {
        try {
            // 参数1: 读物excel文件输入流; 参数2: excel模板类; 参数3: 监听器
            EasyExcel.read(file.getInputStream(), TClue.class, new UploadDataListener(tClueMapper, token))
                    .sheet()
                    .doRead();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Boolean checkPhone(String phone) {
        int count = tClueMapper.selectByCount(phone);
        return count <= 0;
    }

    @Override
    public int addClue(ClueQuery clueQuery) {
        int count = tClueMapper.selectByCount(clueQuery.getPhone());
        if (count > 0) {
            throw new RuntimeException("该手机已经录入过!");
        }
        TClue tClue = new TClue();
        BeanUtils.copyProperties(clueQuery, tClue);

        Integer loginUserId = JWTUtils.parseUserFromJWT(clueQuery.getToken()).getId();
        tClue.setCreateTime(new Date());
        tClue.setCreateBy(loginUserId);
        return tClueMapper.insertSelective(tClue);
    }

    @Override
    public TClue getClueById(Integer id) {
        return tClueMapper.selectDetailById(id);
    }

    @Override
    public int updateClue(ClueQuery clueQuery) {
        TClue tClue = new TClue();
        BeanUtils.copyProperties(clueQuery, tClue);

        Integer loginUserId = JWTUtils.parseUserFromJWT(clueQuery.getToken()).getId();
        tClue.setEditBy(loginUserId);
        tClue.setEditTime(new Date());
        return tClueMapper.updateByPrimaryKeySelective(tClue);
    }
}
